package org.flint.data.structure.leetcode;

import org.apache.commons.lang3.StringUtils;

import java.util.Stack;

/**
 * @author flint92
 */
public class ValidParentheses {


    /**
     * Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
     * determine if the input string is valid.
     *
     * An input string is valid if:
     *
     * Open brackets must be closed by the same type of brackets.
     * Open brackets must be closed in the correct order.
     * Note that an empty string is also considered valid.
     *
     * @param s     String
     * @return      bool
     */
    public boolean isValid(String s) {
        if (s == null) {
            return false;
        }

        if (StringUtils.isBlank(s)) {
            return true;
        }

        Stack<Character> stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c == '(') {
                stack.push(')');
            } else if (c == '{') {
                stack.push('}');
            } else if (c == '[') {
                stack.push(']');
            } else if (stack.isEmpty() || stack.pop() != c) {
                return false;
            }
        }

        return stack.empty();
    }


}
